/*
 * Copyright 2010 Original Author(s)
 * 
 * This file is part of Kommando
 * 
 * Kommando is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Kommando is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Kommando.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.kommando.textfile.objectsource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.kommando.core.util.Assert;

/**
 * {@link TextLine} container.
 * 
 * @author Peter De Bruycker
 */
public class TextLines {

    private List<TextLine> lines = new ArrayList<TextLine>();

    public List<TextLine> getLines() {
        return lines;
    }

    public void appendText(String text) {
        Assert.argumentNotNull("text", text);

        lines.add(new TextLine(this, text));
    }

    public void prependText(String text) {
        Assert.argumentNotNull("text", text);

        lines.add(0, new TextLine(this, text));
    }

    void writeTo(Writer writer) throws IOException {
        Assert.argumentNotNull("writer", writer);

        for (Iterator<TextLine> iterator = lines.iterator(); iterator.hasNext();) {
            TextLine line = iterator.next();

            writer.write(line.getText());
            if (iterator.hasNext()) {
                writer.append(System.getProperty("line.separator"));
            }
        }
    }

    void readFrom(Reader reader) throws IOException {
        Assert.argumentNotNull("reader", reader);

        lines.clear();

        BufferedReader bufferedReader = new BufferedReader(reader);

        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            appendText(line);
        }
    }

    public void deleteLine(TextLine textLine) {
        Assert.argumentNotNull("textLine", textLine);

        lines.remove(textLine);
    }

}
